<?php
/**
 * Created by PhpStorm.
 * User: xiao
 * Date: 2017/11/24
 * Time: 10:39
 */

namespace Home\Controller;


use Common\Api\WxApi;
use Common\Base\BaseController;
use Org\WeChat\WeChat;
use Org\WeChat\WeChatApi;
use Org\WeChat\WeChatUtils;

class WeChatController extends BaseController
{

    public function index()
    {

        $wxApi = new WxApi();
//        $wxApi->valid();            // 验证
        $wxApi->responseMsg();      // 自动回复
    }


    public function test()
    {
        dump('test');
    }




    
    /**
     * 创建菜单
     */
    public function createMenu()
    {
        $data = '{
             "button":[
             {	
                  "type":"click",
                  "name":"口号",
                  "key":"瓷妆"
              },
             {	
                  "type":"view",
                  "name":"微商城",
                  "url":"http://www.baidu.com"
              },
        
              {
                   "name":"微官网",
                   "sub_button":[
                   {	
                       "type":"view",
                       "name":"ooo中心",
                       "url":"http://www.baidu.com"
                    },
                   
                   {	
                       "type":"view",
                       "name":"xxx中心",
                       "url":"http://www.baidu.com"
                    }
        
                   ]
               }]
         }';

        $weChat = new WeChat();
        $accessToken = $weChat->GetAccessToken();
        $url = WeChatApi::getApiUrl('api_create_menus');
        $url .= $accessToken;
        $str = $weChat -> CurlRequest( $url, $data );
        $json = json_decode($str);
        if( $json->errmsg == 'ok' ){
            echo "Create Menus Successfully\n";
        }
    }


    // 获取用户的
    public function getQrcode()
    {

        $userData = M('user')->find(1);

        $userId = $userData['id'];
        $username = $userData['username'];

        $params = array('userId' => $userId, 'nickname' => $username);              // 需要传输的数据
        $data = WeChatUtils::getQrcodeTempData($params);                            // 构建ticket需要传输的数据


        $weChatApi = new WeChatApi();
        $weChat = new WeChat();

        $accessToken = $weChat->GetAccessToken();                                   // 获取微信的accessToken

        $ticketUrl = $weChatApi->getTicketTempUrl($accessToken);                    // 获取微信二维码ticket地址

        $json = $weChat->CurlPostJson($ticketUrl, $data);                           // curl post请求微信接口 获取ticket

        $json = json_decode($json, true);                                           // 解析返回的数据

        $ticket = $json['ticket'];                                                  // 获取ticket数据

        $qrCodeUrl = $weChatApi->getQrcodeUrl($ticket);                                   // 带参数的二维码地址,可以渲染,可以下载

        $this->assign('qrCodeUrl', $qrCodeUrl);

        $this->display('shareQrcode');

    }

}